package area

import (
	"embed"
	"fmt"
	"strings"

	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
)

//go:embed ip2region.xdb
var ip2regionFile embed.FS

var ipBuff []byte

//goland:noinspection GoBoolExpressions
func initRegion() {
	var err error
	// 读取嵌入的文件内容
	ipBuff, err = ip2regionFile.ReadFile("ip2region.xdb")
	if err != nil {
		result := fmt.Errorf("加载归属地数据库数据失败 `%s`: %s", "ip2region.xdb", err)
		panic(result)
	}
}

func queryIpRegion(ip string) (string, error) {
	version := xdb.IPv4
	searcher, err := xdb.NewWithBuffer(version, ipBuff)
	if err != nil {
		return "", fmt.Errorf("创建searcher失败: %v", err)
	}
	defer searcher.Close()

	//startTime := time.Now()
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		return "", fmt.Errorf("查询ip失败(%s): %v", ip, err)
	}
	//log.Printf("查询耗时: %s", time.Since(startTime)) // 打印查询耗时
	return region, nil
}

func GetIpRegion(ip string) (Area, error) {
	// 1、调用IP库查询
	region, err := queryIpRegion(ip)
	if err != nil {
		return Area{}, fmt.Errorf("IP：%s，归属地获取失败", ip)
	}
	// 2、分析查询结果（中国|0|山东省|青岛市|联通）
	regionArr := strings.Split(region, "|")
	provinceKeyword := regionArr[2]
	cityKeyword := regionArr[3]
	// 3、搜索省份
	province, found := SearchProvinceByTitle(provinceKeyword)
	if !found {
		return Area{}, fmt.Errorf("未找到归属省份：%s", region)
	}
	// 4、搜索城市
	city, found := SearchCityByTitle(province.ID, cityKeyword)
	if !found {
		return Area{}, fmt.Errorf("未找到归属城市：%s", region)
	}
	return city, nil
}
